package com.wang.kmp

import android.annotation.SuppressLint
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver

/**
 * 默认配置
 */
@SuppressLint("SetJavaScriptEnabled")
fun WebView.settingsDefault(ui: ComponentActivity) {
    val set = settings
    set.javaScriptEnabled = true
    set.loadWithOverviewMode = true //避免白屏
    set.domStorageEnabled = true //支持页面存储
    set.setSupportMultipleWindows(false)
    set.defaultTextEncodingName = "UTF-8"
    set.javaScriptCanOpenWindowsAutomatically = true
    set.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW//允许http和https混合
    isHorizontalScrollBarEnabled = false
    isVerticalScrollBarEnabled = false
    set.userAgentString = "${set.userAgentString}/AndroidApp"

    ui.lifecycle.addObserver(LifecycleEventObserver { source, event ->
        if (event == Lifecycle.Event.ON_DESTROY) {
            try {
                resetAll()
                destroy()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    })
}

/**
 * 复原重置
 */
fun WebView.resetAll() {
    stopLoading()
    clearHistory()
    clearCache(true)
    loadUrl("about:blank")
}